//
//  UserPhotoUploadViewController.m
//  ChatForHot
//
//  Created by wr on 2018/10/15.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "UserPhotoUploadViewController.h"
#import "UPhotoBottomView.h"
#import "UPhotoListView.h"
#import "HCPhotoCell.h"
#import "HCPhotoCameraCell.h"
#import "HCPhotoManager.h"

#define HOTCHATORIGINAL_MAX_WIDTH 640.0f

@interface UserPhotoUploadViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UPhotoBottomDelegate>


@property(nonatomic, strong) UICollectionView *HOTCHATphotoCollectionView;
@property(nonatomic, strong) UIBarButtonItem *HOTCHATconfirmBar;
@property(nonatomic, strong) NSArray *dataArray;
@property(nonatomic, strong) NSMutableArray *selectArray;
@property(nonatomic, assign) NSInteger HOTCHATcellwidth;
@property(nonatomic, strong) UPhotoBottomView *HOTCHATbottomView;
@property(nonatomic, strong) UPhotoListView *HOTCHATlistview;
@property(nonatomic, strong) NSArray *photoListArray;
@property(nonatomic, assign) BOOL isSendPhoto;
@property(nonatomic, assign) NSInteger selectedRow;
@end

@implementation UserPhotoUploadViewController

- (void)HOTCHATdidInitialized {
    [super HOTCHATdidInitialized];
    
    float cwidth = CGRectGetWidth(self.view.frame);
    if (self.HOTCHATcellwidth == 0) {
        self.HOTCHATcellwidth = (cwidth - 8 - 3.5 * 4) / 5;
        if (self.HOTCHATcellwidth < 100) {
            self.HOTCHATcellwidth = (cwidth - 8 - 3.5 * 3) / 4;
        }
        if (self.HOTCHATcellwidth < 100) {
            self.HOTCHATcellwidth = (cwidth - 8 - 3.5 * 2) / 3;
        }
    }
    
    self.selectArray = [[NSMutableArray alloc] init];
}

- (void)HOTCHATInsertSubViews {
    [super HOTCHATInsertSubViews];
    
    self.HOTCHATconfirmBar = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"", nil) style:(UIBarButtonItemStylePlain) target:self action:@selector(HOTCHATconfirmAction)];
    
    if (self.isSendPhoto) {
        _HOTCHATconfirmBar.title = @"Send";
    }
    self.navigationItem.rightBarButtonItem = self.HOTCHATconfirmBar;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.HOTCHATphotoCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.HOTCHATphotoCollectionView.dataSource = self;
    self.HOTCHATphotoCollectionView.delegate = self;
    self.HOTCHATphotoCollectionView.alwaysBounceVertical = YES;
    [self.HOTCHATphotoCollectionView registerClass:[HCPhotoCell class] forCellWithReuseIdentifier:@"HCPhotoCell"];
    [self.HOTCHATphotoCollectionView registerClass:[HCPhotoCameraCell class] forCellWithReuseIdentifier:@"HCPhotoCameraCell"];
    self.HOTCHATphotoCollectionView.showsHorizontalScrollIndicator = NO;
    self.HOTCHATphotoCollectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.HOTCHATphotoCollectionView];
    
    self.HOTCHATbottomView = [[UPhotoBottomView alloc] init];
    self.HOTCHATbottomView.photoName = @"";
    self.HOTCHATbottomView.delegate = self;
    [self.view addSubview:self.HOTCHATbottomView];
    
    self.HOTCHATlistview = [[UPhotoListView alloc] init];
    self.HOTCHATlistview.delegate = self;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.HOTCHATphotoCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.HOTCHATbottomView.mas_top);
    }];
    [self.HOTCHATbottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
}

- (void)HOTCHATsetNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated {
    [super HOTCHATsetNavigationItemsIsInEditMode:isInEditMode animated:animated];
    
    self.title = NSLocalizedString(@"selGp1", nil);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getDeviceAllPhotos];
}

- (void)getDeviceAllPhotos {
    @weakify(self)
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            if (self.dataArray.count == 0 && status == PHAuthorizationStatusAuthorized) {
                [self HOTCHATgetDeviceTotalPhotos];
            }
        });
    }];
    
    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusDenied) {
    }else{
        [self HOTCHATgetDeviceTotalPhotos];
    }
}

- (void)updateLeftButtonText{
    if (self.isSendPhoto) {
        return;
    }
    if (self.selectArray.count == 0) {
        self.HOTCHATconfirmBar.title = NSLocalizedString(@"userPhoto5", nil);
    }else{
        self.HOTCHATconfirmBar.title = [NSString stringWithFormat:@"%@(%zd/%zd)",NSLocalizedString(@"userPhoto5", nil),self.selectArray.count,self.maxCount];
    }
}

#pragma mark UICollectionDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        HCPhotoCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HCPhotoCameraCell" forIndexPath:indexPath];
        return cell;
    }
    HCPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HCPhotoCell" forIndexPath:indexPath];
    id entity = self.dataArray[indexPath.row - 1];
    cell.entity = entity;
    BOOL isSelected = [self HOTCHATisSelectedPhoto:entity];
    cell.isSelected = isSelected;
    if (self.isSendPhoto) {
        if (isSelected) {
            self.selectedRow = indexPath.row;
        }
    }
    return cell;
}
#pragma mark UICollectionview Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        [self HOTCHATopenTheCamera];
    }else{
        HCPhotoCell *cell = (HCPhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        if (cell.isSelected) {
            [self.selectArray removeObject:cell.entity];
            cell.isSelected = NO;
        }else{
            if (self.isSendPhoto) {
                if (self.selectArray.count > 0) {
                    [self.selectArray removeAllObjects];
                    if (self.selectedRow > 0 && self.selectedRow <= self.dataArray.count) {
                        NSIndexPath *ipath = [NSIndexPath indexPathForItem:self.selectedRow inSection:0];
                        [self.HOTCHATphotoCollectionView reloadItemsAtIndexPaths:@[ipath]];
                    }
                }
                self.selectedRow = indexPath.row;
                [self.selectArray addObject:cell.entity];
                cell.isSelected = YES;
            }else{
                if (self.selectArray.count >= self.maxCount) {
                    [NetWorkTool HOTCHATshowMessage:[NSString stringWithFormat:NSLocalizedString(@"userPhoto4", nil),self.maxCount]];
                    return;
                }else{
                    [self.selectArray addObject:cell.entity];
                    cell.isSelected = YES;
                }
            }
        }
    }
    [self updateLeftButtonText];
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 3.5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 3.5;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.HOTCHATcellwidth, self.HOTCHATcellwidth);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(4, 4, 4, 4);
}

#pragma mark - Actions

- (void)HOTCHATconfirmAction{
    if (self.delegate && [self.delegate respondsToSelector:@selector(HOTCHATselectedPhotoArray:)]) {
        [self.delegate HOTCHATselectedPhotoArray:self.selectArray];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)HOTCHATisSelectedPhoto:(id)entity{
    if (self.selectArray.count == 0) {
        return NO;
    }
    NSString *id1 = [[HCPhotoManager shareManager] getAssetIdentifier:entity];
    NSString *id2 = nil;
    for (id sEntity in self.selectArray) {
        id2 = [[HCPhotoManager shareManager] getAssetIdentifier:sEntity];
        if ([id1 isEqualToString:id2]) {
            return YES;
        }
    }
    return NO;
}

#pragma -mark getalldevicephoto
- (void)HOTCHATgetDeviceTotalPhotos{
    @weakify(self)
    [[HCPhotoManager shareManager] getAllAlbums:NO allowPickingImage:YES completion:^(NSArray<HCAlbumModel *> *modelsll) {
        @strongify(self)
        self.photoListArray = modelsll;
        if (modelsll.count > 0) {
            [self HOTCHATgetPhotos:[modelsll firstObject]];
        }
    }];
}
- (void)HOTCHATgetPhotos:(HCAlbumModel *)HCam{
    @weakify(self)
    self.HOTCHATbottomView.photoName = HCam.name;
    [[HCPhotoManager shareManager] getAssetsFromFetchAlbumModel:HCam allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<HCAssetModel *> *models) {
        @strongify(self)
        self.dataArray = [[models reverseObjectEnumerator] allObjects];
        self.selectedRow = -1;
        [self.HOTCHATphotoCollectionView performSelectorOnMainThread:@selector(reloadData) withObject:self waitUntilDone:NO];
    }];
}

- (void)HOTCHATsetListShow{
    self.HOTCHATbottomView.isShowList = YES;
    [self.HOTCHATlistview HOTCHATshowInView:self.view.window.rootViewController.view array:self.photoListArray];
}

- (void)HOTCHAThiddenListView{
    [self.HOTCHATlistview HOTCHATcloseListView];
    self.HOTCHATbottomView.isShowList = NO;
}

- (void)HOTCHATcloseListView{
    self.HOTCHATbottomView.isShowList = NO;
}

#pragma mark - opencamera

- (void)HOTCHATopenTheCamera{
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    }else{
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    [imagePicker setDelegate:self];
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    portraitImg = [self imageByScalingToMaxSize:portraitImg];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self.selectArray addObject:portraitImg];
    [self HOTCHATconfirmAction];
}

- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < HOTCHATORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = HOTCHATORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (HOTCHATORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = HOTCHATORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (HOTCHATORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if (widthFactor > heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    UIGraphicsEndImageContext();
    return newImage;
}

@end
